package com.erp.module.crm.xXCrm.jiaoLiu

import android.app.Activity
import android.content.Intent
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.AdapterView
import androidx.appcompat.app.AlertDialog
import com.erp.activity.BaseActivity
import com.erp.activity.ChaKanTuZhiAvtivity
import com.erp.myAdapter.GaugeivGvAdapter1
import com.erp.myAdapter.GvfileAdapter
import com.erp.bean.ClientJiaoliuBean
import com.erp.bean.ImgBean
import com.erp.Interface.OnUserDataInterface
import com.erp.permission.PermissionListener
import com.erp.R
import com.erp.util.Dialogutil
import com.erp.util.Httputil
import com.erp.util.Myutil
import com.erp.util.PermissionUtils
import com.erp.module.crm.xXCrm.ClientKActivity
import com.erp.module.crm.xXCrm.FragmentClientseight
import kotlinx.android.synthetic.main.activity_jiaoliu.*
import kotlinx.android.synthetic.main.header_knoya.*
import org.json.JSONArray
import org.json.JSONObject

/**
 * Created by Administrator on 2018/6/14/014.
 * 作者：刘洋
 */
class JiaoLiuKActivity : BaseActivity(), View.OnClickListener {

    private val a = "JiaoLiuKActivity"
    lateinit var bean: ClientJiaoliuBean
    lateinit var gvaapter: GaugeivGvAdapter1
    lateinit var gvfileaapter: GvfileAdapter
    lateinit var updatedialog: AlertDialog
    override fun getLayoutId(): Int {
        activityname = a
        return R.layout.activity_jiaoliu
    }

    override fun initCreate() {
        bean = FragmentClientseight.bean
        Log.d("TAAG", bean.toString())
        gvfileaapter = GvfileAdapter(bean.listfileid, this)
        GvGaugeFile.adapter = gvfileaapter
        gvaapter = GaugeivGvAdapter1(bean.listimg, this)
        GvGaugeImg.adapter = gvaapter
        iv_header_left.visibility = View.VISIBLE
        tv_header_title.text = "交流记录"
//        tv_header_right.visibility = View.VISIBLE
//        tv_header_right.text = "保存"
        iv_header_left.setOnClickListener(this)
        tv_header_right.setOnClickListener(this)
        TvCommunicationTime.setOnClickListener(this)
        BtBaocun.setOnClickListener(this)
        TvAppointmentCommunication.setOnClickListener(this)
        Myutil.setet(bean.relative_people, TvAssPeople)
        Myutil.setet(bean.content, TvContent)
        Myutil.settv(Myutil.getdata(bean.communication_time), TvCommunicationTime)
        Myutil.settv(Myutil.getdata(bean.appointment_communication), TvAppointmentCommunication)
        onClick()
    }

    override fun onClick(v: View?) {
        when (v) {
            iv_header_left -> finish()
            TvAppointmentCommunication -> {
                Dialogutil.showBottoPopupWindow(TvAppointmentCommunication, "选择售后开始时间", TvAppointmentCommunication.text.toString(), this@JiaoLiuKActivity)
            }
            TvCommunicationTime -> {
                Dialogutil.showBottoPopupWindow(TvCommunicationTime, "选择售后开始时间", TvCommunicationTime.text.toString(), this@JiaoLiuKActivity)
            }
            BtBaocun -> {
                val jo = xiugai()
                updatedialog = Myutil.showupdatedialog(this@JiaoLiuKActivity, "正在保存", false)
                Httputil.cleanclient(this@JiaoLiuKActivity, ClientKActivity.getid(), jo, object : OnUserDataInterface {
                    override fun onUserData(data: String?) {
                        updatedialog.dismiss()
                        Log.d("TAAG", "data=" + data)
                        Myutil.MyTost("保存成功")
                        val i = Intent()
                        i.putExtra("data", data)
                        setResult(Activity.RESULT_OK, i)
                        finish()
                    }

                    override fun onNot(throwable: String?) {
                        updatedialog.dismiss()
                        Log.d("TAAG", "throwable=" + throwable)
                    }
                })
            }
        }
    }

    private fun onClick() {
        /**
         * 删除图片
         */
        GvGaugeImg.onItemLongClickListener = AdapterView.OnItemLongClickListener { parent, view, position, id ->
            if (position < bean.listimg.size) {
                val dialog = AlertDialog.Builder(this@JiaoLiuKActivity)
                dialog.setTitle("提示")
                dialog.setMessage("确定要删除这条交流记录问题?")
                dialog.setPositiveButton("确定") { dialog, which ->
                    bean.listimg.removeAt(position)
                    gvaapter.notifyDataSetChanged()
                }
                dialog.setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                dialog.show()
                true
            } else {
                true
            }
        }
        /**
         * 查看图片
         */
        GvGaugeImg.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            if (position < bean.listimg.size) {
                val intent = Intent(this@JiaoLiuKActivity, ChaKanTuZhiAvtivity::class.java)
                val urls: ArrayList<String> = ArrayList()
                urls.add(bean.listimg[position].imguri)
                intent.putStringArrayListExtra("url", urls)
                startActivity(intent)
            } else if (bean.listimg.size == position) {
                Dialogutil.photodialog(this@JiaoLiuKActivity, null)
            }
        }
        /**
         * 下载附件
         */
        GvGaugeFile.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            PermissionUtils.isupdate(this@JiaoLiuKActivity, object : PermissionListener {
                override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                    Dialogutil.downloaddialog(bean.listfileid[position], this@JiaoLiuKActivity)
                }

                override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                    Myutil.MyTost("没有权限，无法下载")
                }
            })
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(data==null){
            return
        }
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                99 -> {
                    val selectedImage = data.data
                    val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
                    if(selectedImage != null){
                        val c = contentResolver.query(selectedImage, filePathColumns, null, null, null)
                        c!!.moveToFirst()
                        val columnIndex = c.getColumnIndex(filePathColumns[0])
                        val imagePath = c.getString(columnIndex)
                        addphoto(imagePath)
                    }

                }
                100 -> {
                    val name = data.getStringExtra("dir")
                    addphoto(name)
                }
            }
        }
    }
    private fun addphoto(name: String) {
        Myutil.getbt(this@JiaoLiuKActivity, name,object : OnUserDataInterface{
            override fun onUserData(data: String?) {
                val photo = ImgBean()
                photo.imguri = name
                if(data!=null){
                    photo.data=data
                }
                bean.listimg.add(photo)
                gvaapter.notifyDataSetChanged()
            }

            override fun onNot(throwable: String?) {
               Myutil.MyTost("获取照片失败")
            }

        })

    }
    private fun xiugai(): JSONObject {
        var jo = JSONObject()
        try {
            val jiaoliu = JSONObject()
            jiaoliu.put("id", bean.id)
            jiaoliu.put("relative_people", TvAssPeople.text.toString())
            jiaoliu.put("communication_time", Myutil.getdata(TvCommunicationTime.text.toString()))
            jiaoliu.put("content", TvContent.text.toString())
            jiaoliu.put("appointment_communication_time", Myutil.getdata(TvAppointmentCommunication.text.toString()))
            jiaoliu.put("isdelete", false)
            val ivjv = JSONArray()
            for (i in 0 until bean.listfileid.size) {
                val jj = JSONObject()
                jj.put("fid", bean.listfileid.get(i))
                ivjv.put(jj)
            }
            for (i in 0 until bean.listimg.size) {
                val jj = JSONObject()
                if (bean.listimg[i].imgid != "") {
                    jj.put("fid", bean.listimg[i].imgid)
                    ivjv.put(jj)
                }
                if(bean.listimg[i].imgid==""){
                    jj.put("filename",bean.listimg[i].imguri.split("/")[bean.listimg[i].imguri.split("/").size-1].trim() )
                    jj.put("filecontents",bean.listimg[i].data)
                    ivjv.put(jj)
                }
            }
            jiaoliu.put("communication_log_attachment", ivjv)
            jo.put("operations-add", jiaoliu)
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("TAAAG", "--------------" + e.toString())
        }
        return jo
    }
}